package com.example.algorithm.greedy;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author : zhy
 * @since : 2022/8/31
 * 合并数组
 */
public class MergeArray {

    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (x, y) -> Integer.compare(x[0], y[0]));
        int len = intervals.length;
        int start = intervals[0][0];
        int right = intervals[0][1];
        List<int[]> list = new LinkedList<>();
        for (int i = 1; i < len; i++) {
            if (intervals[i][0] > right) {
                list.add(new int[]{start, right});
                start = intervals[i][0];
                right = intervals[i][1];
            } else {
                right = Math.max(right, intervals[i][1]);
            }
        }
        list.add(new int[]{start, right});
        return list.toArray(new int[list.size()][]);
    }

    public static void main(String[] args) {
        MergeArray mergeArray = new MergeArray();
        int [][]can={{1,3},{2,6},{8,10},{15,18}};
        int[][] merge = mergeArray.merge(can);
        for(int []a:merge)
        {
            System.out.println(a[0]+"-----"+a[1]);
        }
    }
}
